#include <stdio.h>
#include <thread>
#include <math.h>

#define SHM_QUEUE_IMPLEMENTATION
#include "shm_queue.h"


bool running = true;

int main() {
  shm_queue_t wqueue;
  shm_queue_t rqueue;

  shm_queue_options_t options;
  options.elem_count = 128;
  options.elem_size = 1024;
  options.mode = SHM_QUEUE_MODE_WRITE;
  options.name = "test";
  int rslt = shm_queue_open(&wqueue, &options);

  printf("sq_open ret:%d\n", rslt);

  options.mode = SHM_QUEUE_MODE_READ;
  rslt = shm_queue_open(&rqueue, &options);
  printf("sq_open ret:%d\n", rslt);

  std::thread wthread([&wqueue]() {
    while (running) {
      static const char str[] = "4321fdsafdsafdsafdsaf432143124321111111111143214rewrewqrewqrewrewqrewqr4321fdsafdsafdsafdsaf432143124321111111111143214rewrewqrewqrewrewqrewqr4321fdsafdsafdsafdsaf432143124321111111111143214rewrewqrewqrewrewqrewqr";
      int rslt = shm_queue_write(&wqueue, (void*)str, rand() % sizeof(str));
      //printf("shm_queue_write ret:%d\n", rslt);
      std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
  });

  std::thread rthread([&rqueue]() {
    char buffer[1024];
    while (running) {
      int rslt = shm_queue_read(&rqueue, buffer, sizeof(buffer));
      if (rslt > 0) {
        printf("shm_queue_read size:%d msgid:%d\n", rslt, rqueue.rmsgid);
      } else {
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
      }
    }
  });

  getchar();
  running = false;
  wthread.join();
  rthread.join();
  printf("finish\n");
  shm_queue_close(&wqueue);
  shm_queue_close(&rqueue);

  return 0;
}
